package com.ikunikun.controller;

import com.ikunikun.constant.MessageConstant;
import com.ikunikun.result.Result;
import com.ikunikun.utils.AliOssUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.UUID;

/**
 * 通用接口，文件上传下载
 */
@Slf4j
@Api(tags = "通用接口")
@RestController
@RequestMapping("/admin/common")
public class CommonController {

	@Resource
	private AliOssUtil aliOssUtil;

	@PostMapping("/upload")
	@ApiOperation("文件上传")
	// 该参数名需要与前端文件的参数名一致
	public Result<String>  upload(MultipartFile file){
		log.info("文件上传中,name: {}", file.getOriginalFilename());
		try {
			String originalFilename = file.getOriginalFilename();
			String substring = originalFilename.substring(originalFilename.lastIndexOf("."));
			String upload = aliOssUtil.upload(file.getBytes(), UUID.randomUUID() + substring);
			return Result.success(upload);
		} catch (IOException e) {
			log.error("文件上传失败：{}", e.getMessage());
		}
		return Result.error(MessageConstant.UPLOAD_FAILED);
	}
}
